package com.example.controller;

import com.example.bean.User;
import com.example.service.UserService;
import com.example.tools.EmailTools;
import com.example.tools.RandomNum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    UserService userService;


    // 用户注册
    @RequestMapping("/regist")
    public String regist(@RequestParam("username")String username,
                       @RequestParam("password")String password,
                       @RequestParam("email")String email,
                       @RequestParam("phone")String phone,
                       @RequestParam("yanzheng")String code,
                       Model model){

        // 比对验证码是否正确
        if(code == redisTemplate.boundValueOps(email).get()){
            // 注册成功
            User user = new User(null, username, password, email, phone);
            userService.addUser(user);

            model.addAttribute("msg", "注册成功！！");
            return "regist";
        }else{
            // 注册失败
            model.addAttribute("msg", "注册失败！！");
            return "regist";
        }
    }


    // 获取邮箱验证码
    @RequestMapping("/sendEmail")
    public void sendEmail(@RequestParam("email")String email){
        int r_num = RandomNum.getRandomNum();
        String code = EmailTools.sendRnumEmail(email, r_num, redisTemplate);
    }


    // 用户登录
    @RequestMapping("/login")
    public String login(@RequestParam("email")String email,
                      @RequestParam("password")String password,
                      Model model){
        User user = new User(email, password);

        User findUser = userService.findDone(user);
        if(findUser != null){

            if (findUser.getStatus() == 0){
                System.out.println(findUser);
                System.out.println("root登录成功！");
                return "root_index";
            }else if(findUser.getStatus() == 1){
                System.out.println(findUser);
                System.out.println("admin用户登录成功！");
                return "admin_index";
            }else{
                System.out.println("登录身份验证错误！！");
                model.addAttribute("msg", "登录身份验证错误！！");
                return "login";
            }

        }else{
            System.out.println("邮箱或者密码错误！！");
            model.addAttribute("msg", "邮箱或者密码错误！！");
            return "login";
        }
    }

}
